package com.my.algorithmlearning.leetcode;

import com.my.algorithmlearning.entity.ListNode;
import org.springframework.util.Assert;

/**
 * @ClassName AddTwoNumbers
 * @Description AddTwoNumbers
 * @Author wanghaiwei
 * @Date 2023/1/30 14:55
 */
public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carryFlag = 0;
        ListNode result = new ListNode(0);
        ListNode headOfResult = result;
        while (l1 != null || l2 != null) {
            int addLeft = 0;
            int addRight = 0;
            if (l1 != null) {
                addLeft = l1.val;
            }
            if (l2 != null) {
                addRight = l2.val;
            }
            int sum = addLeft + addRight + carryFlag;
            int newVal = sum % 10;
            carryFlag = sum >= 10 ? 1 : 0;
            result.next = new ListNode(newVal);
            result = result.next;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (carryFlag > 0) {
            result.next = new ListNode(1);
        }
        return headOfResult.next;
    }

    public static void main(String[] args) {
        AddTwoNumbers solution = new AddTwoNumbers();
        ListNode l1 = ListNode.convertArrayToListNode(new int[]{9,9,9,9,9,9,9});
        ListNode l2 = ListNode.convertArrayToListNode(new int[]{9,9,9,9});
        String result = solution.addTwoNumbers(l1, l2).toString();
        Assert.isTrue("8,9,9,9,0,0,0,1".equals(result), "l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]计算错误，预期Output: [8,9,9,9,0,0,0,1]，实际: " + result);
    }
}
